//
//  ZLTableViewController.m
//  QuickCure
//
//  Created by 小灰灰 on 16/9/13.
//  Copyright © 2016年 haoge. All rights reserved.
//

#import "ZLTableViewController.h"
#import "LHdataModel.h"
#import "Utils.h"
#import "UserDTO.h"
#import "NSString+pinyin.h"
#import "UIView+Frame.h"

@interface ZLTableViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSArray *dataListArray;
@property(nonatomic,strong)UITextField *searchBar;
@property(nonatomic,strong)UITableView *tableView;
/** 存储模型的数组 */
@property (nonatomic, strong) NSMutableArray *storeUserDTOList;

/** 搜索数组 */
@property (nonatomic, strong) NSMutableArray *seachUserDTOList;

/** 是否在搜索状态 */
@property (nonatomic, assign) BOOL isSearchState;
@end

@implementation ZLTableViewController
#pragma mark  - Lazy
- (NSMutableArray *)storeUserDTOList{
    if (_storeUserDTOList == nil) {
        _storeUserDTOList = [[NSMutableArray alloc] init];
    }
    return _storeUserDTOList;
}

- (NSMutableArray *)seachUserDTOList{
    if (_seachUserDTOList == nil) {
        _seachUserDTOList = [[NSMutableArray alloc] init];
    }
    return _seachUserDTOList;
}

-(void)setDataListArray:(NSArray *)dataListArray
{
    
    _dataListArray = dataListArray;
    
    [self loadData];
    
    }
-(void)loadData{
    
        for (int i = 0; i < self.dataListArray.count; ++i) {
            
            UserDTO *dto = [[UserDTO alloc] init];
            LHdataModel *model = self.dataListArray[i];
            
            //转拼音
            NSString *PinYin =  [ model.ci3_name transformToPinyin];
            
            //首字母
            NSString *FirstLetter = [ model.ci3_name transformToPinyinFirstLetter];
            
            //        NSLog(@"pinyin = %@ -- %@",PinYin,FirstLetter);
            
            dto.name =  model.ci3_name;
            dto.namePinYin = PinYin;
            dto.nameFirstLetter = FirstLetter;
            
            [self.storeUserDTOList addObject:dto];
        }
        
        [self.tableView reloadData];
    }


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView =[[UITableView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.tableView];
    UIView *view =[[UIView alloc] init];
    self.tableView.tableFooterView = view;
    
    [LHdataModel dataListWithSuccessBlock:^(NSArray *dataArr) {
        self.dataListArray = dataArr;
        [self.tableView reloadData];
    }
       errorBlock:^{
        
    }];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self setSearchBar];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}
//模糊搜索框
-(void)setSearchBar
{
    self.searchBar = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 160, 30)];
    self.searchBar.backgroundColor = [UIColor whiteColor];
    [self.searchBar setBorderStyle:UITextBorderStyleRoundedRect];
    [self.searchBar setPlaceholder:@"请输入关键字"];
    [self.searchBar setFont:[UIFont systemFontOfSize:14]];
    [self.searchBar setTintColor:[UIColor blueColor]];
    [self.navigationItem setTitleView:self.searchBar];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:nil];
}
/** 监听 */
- (void)textChange:(NSNotification *)note{
    
    UITextField *textField = (UITextField *)[note object];
    
    //如果项目大，搜索的地方多，就要使用多线程，然后在刷新tableview的时候，回到主线程
    [self startSearch:textField.text];
}

//开始搜索
-(void)startSearch:(NSString *)string{
    
    if (self.seachUserDTOList.count > 0) {
        
        [self.seachUserDTOList removeAllObjects];
    }
    
    //开始搜索
    NSString *key = string.lowercaseString;
    NSMutableArray *tempArr = [NSMutableArray array];
    
    // NSLog(@"key = %@",key);
    
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        
        [self.storeUserDTOList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UserDTO *dto = self.storeUserDTOList[idx];
            
            //担心框架有时候会误转，再次都设置转为小写
            NSString *name = dto.name.lowercaseString;
            NSString *namePinyin = dto.namePinYin.lowercaseString;
            NSString *nameFireLetter = dto.nameFirstLetter.lowercaseString;
            
            NSRange rang1 = [name rangeOfString:key];
            if (rang1.length>0) { ///比牛 -比
                
                [tempArr addObject:dto];
            }else{
                
                if ([nameFireLetter containsString:key]) { //bn - b
                    
                    [tempArr addObject:dto];
                    
                }else{  //ershou
                    
                    if ([nameFireLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([namePinyin containsString:key] ) {
                            [tempArr addObject:dto];
                        }
                    }
                }
            }
        }];
        
        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.seachUserDTOList containsObject:tempArr[idx]]) {
                
                [self.seachUserDTOList addObject:tempArr[idx]];
            }
        }];
        
        //NSLog(@"self.searchResultList  = %@",self.seachUserDTOList);
        self.isSearchState = YES;
    }else{
        
        self.isSearchState = NO;
    }
    
    [self.tableView reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
    //return self.dataListArray.count;
    UILabel *noResultLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    
    noResultLab.font = [UIFont systemFontOfSize:20];
    noResultLab.textColor = [UIColor lightGrayColor];
    noResultLab.textAlignment = NSTextAlignmentCenter;
    noResultLab.hidden = YES;
    noResultLab.text = @"抱歉！没有搜索到相关数据";
    tableView.backgroundView = noResultLab;
    
    
    if (_isSearchState) {
        
        if (self.seachUserDTOList.count > 0) {
            
            noResultLab.hidden = YES;
            
            return self.seachUserDTOList.count;
            
        }else{
            
            noResultLab.hidden = NO;
            
            return 0;
        }
    }else{
        
        return self.storeUserDTOList.count;
    }

    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    UserDTO *dto = nil;
    
    if (_isSearchState) {
        
        dto = self.seachUserDTOList[indexPath.row];
    }else{
        
        dto = self.storeUserDTOList[indexPath.row];
    }
    
    cell.textLabel.text = dto.name;

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //将数据返回
    LHdataModel *model =self.dataListArray[indexPath.row];

    if(self.dataStrBlock)
    {
        self.dataStrBlock(model.ci3_name);
    }
    //返回上层控制器
    [self.navigationController popViewControllerAnimated:YES];
}

@end
